package com.kefu.admin.utils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;

/**
 * 发送请求 httpclient封装 2015年6月6日11:18:32 liuwei
 */

@SuppressWarnings("deprecation")
public class SendRequest {
	private static final Logger logger = Logger.getLogger(SendRequest.class);

	/**
	 * 发送Get请求
	 * 
	 * @param url
	 *            请求的地址
	 * @param headers
	 *            请求的头部信息
	 * @param params
	 *            请求的参数
	 * @param encoding
	 *            字符编码
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	@SuppressWarnings("resource")
	public static Result sendGet(String url, Map<String, String> headers, Map<String, String> params, String encoding,
			boolean duan) throws ClientProtocolException, IOException {

		
		DefaultHttpClient client = new DefaultHttpClient();
		url = url + (null == params ? "" : assemblyParameter(params));
		HttpGet hp = new HttpGet(url);
		if (null != headers)
			hp.setHeaders(assemblyHeader(headers));
		HttpResponse response = client.execute(hp);
		if (duan)
			hp.abort();
		HttpEntity entity = response.getEntity();
		Result result = new Result();
		result.setCookie(assemblyCookie(client.getCookieStore().getCookies()));
		result.setStatusCode(response.getStatusLine().getStatusCode());
		result.setHeaders(response.getAllHeaders());
		result.setHttpEntity(entity);
		return result;
	}

	public static Result sendGet(String url, Map<String, String> headers, Map<String, String> params, String encoding)
			throws ClientProtocolException, IOException {
		return sendGet(url, headers, params, encoding, false);
	}

	/**
	 * 发送Post请求
	 * 
	 * @param url
	 *            请求的地址
	 * @param headers
	 *            请求的头部信息
	 * @param params
	 *            请求的参数
	 * @param encoding
	 *            字符编码
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	@SuppressWarnings("resource")
	public static Result sendPost(String url, Map<String, String> headers, Map<String, String> params, String encoding)
			throws ClientProtocolException, IOException {

		
		DefaultHttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(url);
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		for (String temp : params.keySet()) {
			list.add(new BasicNameValuePair(temp, params.get(temp)));
		}
		post.setEntity(new UrlEncodedFormEntity(list, encoding));

		if (null != headers)
			post.setHeaders(assemblyHeader(headers));

		HttpResponse response = client.execute(post);

		HttpEntity entity = response.getEntity();

		Result result = new Result();
		result.setStatusCode(response.getStatusLine().getStatusCode());
		result.setHeaders(response.getAllHeaders());
		result.setCookie(assemblyCookie(client.getCookieStore().getCookies()));
		result.setHttpEntity(entity);
		// client.close();
		return result;
	}

	public static int sendPostBody(String urls, String bodys, Map<String, String> params, String encodings)
			throws ClientProtocolException, IOException {

		
		HttpClient client = new HttpClient();
		urls = urls + (null == params ? "" : assemblyParameter(params));
		PostMethod post = new PostMethod(urls);
		post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, encodings);
		post.setRequestBody(bodys);
		return client.executeMethod(post);
	}

	/**
	 * 文件上传
	 * 
	 * @param url
	 *            请求的地址
	 * @param headers
	 *            请求的头部信息
	 * @param params
	 *            请求的参数
	 * @param encoding
	 *            字符编码
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static Result uploadFile(String url, Map<String, String> headers, Map<String, String> params,
			String filepath) throws ClientProtocolException, IOException {
		File targetFile = new File(filepath);// TODO 指定上传文件
		boolean flag = true;
		for (String temp : params.keySet()) {
			if (flag) {
				url = url + "?" + temp + "=" + params.get(temp);
				flag = false;
			} else {
				url = url + "&" + temp + "=" + params.get(temp);
			}
		}
		PostMethod filePost = new PostMethod(url);
		Result result = new Result();
		try {
			Part[] parts = { new FilePart(targetFile.getName(), targetFile) };
			filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
			if (null != headers && headers.size() > 0) {
				for (String str : headers.keySet()) {
					filePost.setRequestHeader(str, headers.get(str));
				}
			}
			HttpClient client = new HttpClient();
			client.getHttpConnectionManager().getParams().setConnectionTimeout(100);
			int status = client.executeMethod(filePost);
			HttpClientParams resultParams = client.getParams();
			result.setStatusCode(status);
			result.setCookie(resultParams.getCookiePolicy());
			result.setOtherContent(filePost.getResponseBodyAsString());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			filePost.releaseConnection();
		}
		return result;
	}

	/**
	 * 组装头部信息
	 * 
	 * @param headers
	 * @return
	 */
	public static Header[] assemblyHeader(Map<String, String> headers) {
		Header[] allHeader = new BasicHeader[headers.size()];
		int i = 0;
		for (String str : headers.keySet()) {
			allHeader[i] = new BasicHeader(str, headers.get(str));
			i++;
		}
		return allHeader;
	}

	/**
	 * 组装Cookie
	 * 
	 * @param cookies
	 * @return
	 */
	public static String assemblyCookie(List<Cookie> cookies) {
		StringBuffer sbu = new StringBuffer();
		for (Cookie cookie : cookies) {
			sbu.append(cookie.getName()).append("=").append(cookie.getValue()).append(";");
		}
		if (sbu.length() > 0)
			sbu.deleteCharAt(sbu.length() - 1);
		return sbu.toString();
	}

	/**
	 * 组装请求参数
	 * 
	 * @param parameters
	 * @return
	 */
	public static String assemblyParameter(Map<String, String> parameters) {
		String para = "?";
		for (String str : parameters.keySet()) {
			para += str + "=" + parameters.get(str) + "&";
		}
		return para.substring(0, para.length() - 1);
	}

	// TODO demo
	public static void main(String[] args) {
//		try {
//			Des des = new Des("SSOResetUserDefault");
//			Map<String, String> param = new HashMap<String, String>();
//			param.put("ver", "1");
//			param.put("_method_", des.encrypt("saveFence"));
//			param.put("userId", des.encrypt("2"));
//			param.put("account", des.encrypt("admin"));
//			param.put("password", des.encrypt("123456"));
//			Result result = SendRequest.sendPost("http://127.0.0.1:9080//api/config/v1/hello", null, param, "utf-8");
//			// SendRequest.u
//			String str = result.getHtml(result, "utf-8");
//			System.out.println(str);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
		Map<String, String> paramMap = new HashMap<String, String>();
		Map<String, String> head = new HashMap<String, String>();
		head.put("","");

		String url = "https://mp.weixin.qq.com/s?__biz=MzU1MjkzNDAxOQ==&mid=2247483751&idx=1&sn=84f41c6cfa07284a06229698fc4ce347&scene=19#wechat_redirect";

		try {
			Result result= SendRequest.sendPost(url, null, paramMap, "utf-8");
			String str = result.getHtml(result, "utf-8");
			System.out.println(str);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

}